package com.example.tb_log.log;

import android.util.Log;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 将日志保存到文件的Printer
 */
public class TbFilePrinter implements TbLogPrinter {
    private static final String TAG = "TbFilePrinter";
    private final String logPath;
    private final SimpleDateFormat dateFormat;
    private FileOutputStream fos;
    private File logFile;

    public TbFilePrinter(String logPath) {
        this.logPath = logPath;
        this.dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        initLogFile();
    }

    private void initLogFile() {
        try {
            File dir = new File(logPath);
            if (!dir.exists() && !dir.mkdirs()) {
                Log.e(TAG, "创建日志目录失败: " + logPath);
                return;
            }

            // 使用日期作为文件名
            String fileName = "tb_log_" + dateFormat.format(new Date()) + ".txt";
            logFile = new File(dir, fileName);

            if (!logFile.exists()) {
                logFile.createNewFile();
            }

            fos = new FileOutputStream(logFile, true);
        } catch (IOException e) {
            Log.e(TAG, "初始化日志文件失败", e);
        }
    }

    @Override
    public void print(@NonNull TbLogConfig config, int level, String tag, @NonNull String printString) {
        if (fos == null) {
            return;
        }

        try {
            String time = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
            String levelStr = getLevelString(level);
            String logContent = String.format("%s %s/%s: %s\n", time, levelStr, tag, printString);

            fos.write(logContent.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            Log.e(TAG, "写入日志失败", e);
        }
    }

    private String getLevelString(int level) {
        switch (level) {
            case TbLogType.V:
                return "V";
            case TbLogType.D:
                return "D";
            case TbLogType.I:
                return "I";
            case TbLogType.W:
                return "W";
            case TbLogType.E:
                return "E";
            default:
                return "?";
        }
    }


}
